package com.zhucai.credit.service.impl.transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.zhucai.credit.bean.CreditApplication;
import com.zhucai.credit.bean.CreditInvoice;
import com.zhucai.credit.bean.CreditProduct;
import com.zhucai.credit.bean.CreditRecord;
import com.zhucai.credit.bean.CreditRecordTime;
import com.zhucai.credit.bean.EntAccount;
import com.zhucai.credit.bean.OperRecord;
import com.zhucai.credit.common.CommonEnums.AccCheckStatus;
import com.zhucai.credit.common.CommonEnums.CrAprovalStatus;
import com.zhucai.credit.common.CommonEnums.CrProdType;
import com.zhucai.credit.common.CommonEnums.CreditStatus;
import com.zhucai.credit.common.CommonEnums.CreditUnusualStatus;
import com.zhucai.credit.common.CommonEnums.EnCrStatus;
import com.zhucai.credit.common.CommonEnums.EntType;
import com.zhucai.credit.common.CommonEnums.OperType;
import com.zhucai.credit.common.CommonEnums.ZhuCaiProdType;
import com.zhucai.credit.common.EnumHelper;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.common.MyPage;
import com.zhucai.credit.exception.SubmitCcbException;
import com.zhucai.credit.form.CreditRecordForm;
import com.zhucai.credit.model.CreditApplicationEntity;
import com.zhucai.credit.model.CreditInvoiceEntity;
import com.zhucai.credit.model.CreditProductEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.model.CreditRecordTimeEntrity;
import com.zhucai.credit.model.EntAccountEntity;
import com.zhucai.credit.model.EntCertificateEntity;
import com.zhucai.credit.model.EntCrProdEntity;
import com.zhucai.credit.model.OperRecordEntity;
import com.zhucai.credit.model.PaymentOrderEntity;
import com.zhucai.credit.model.PaymentPlanEntity;
import com.zhucai.credit.model.PaymentRelationEntity;
import com.zhucai.credit.monitor.service.INotificationService;
import com.zhucai.credit.repository.CashierOrderItemRepository;
import com.zhucai.credit.repository.CreditApplicationRepository;
import com.zhucai.credit.repository.CreditInvoiceRepository;
import com.zhucai.credit.repository.CreditProductRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.repository.CreditRecordTimeRepository;
import com.zhucai.credit.repository.EntAccountRepository;
import com.zhucai.credit.repository.EntCertificateRepository;
import com.zhucai.credit.repository.EntCrProdEntityRepository;
import com.zhucai.credit.repository.FinanceAccountOperationRepository;
import com.zhucai.credit.repository.FinanceDebitRepository;
import com.zhucai.credit.repository.FinanceDrawRepository;
import com.zhucai.credit.repository.FinanceRepaymentRepository;
import com.zhucai.credit.repository.OperRecordRepository;
import com.zhucai.credit.repository.PaymentOrderRepository;
import com.zhucai.credit.repository.PaymentPlanRepository;
import com.zhucai.credit.repository.PaymentRelationRepository;
import com.zhucai.credit.service.CreditUserService;
import com.zhucai.credit.service.impl.ccb.CCBSericeImpl;
import com.zhucai.credit.service.impl.loop.OrderLoopService;
import com.zhucai.credit.service.impl.problem.ProblemSericeImpl;
import com.zhucai.credit.utils.SqlResultUtil;
import com.zhucai.credit.utils.TimeUtils;

/**
 * 供应商接口实现 2017年9月19日
 * 
 * @author hsg
 */
@Service("creditUserService")
@com.alibaba.dubbo.config.annotation.Service(version = "1.0.0")
public class CreditUserServiceImplT implements CreditUserService {
	private static final Logger logger = LoggerFactory.getLogger(CreditUserServiceImplT.class);
	@Autowired
	private EntAccountRepository entAccountRepository;
	@Autowired
	private EntCertificateRepository entCertificateRepository;
	@Autowired
	private OperRecordRepository operRecordRepository;
	@Autowired
	private CreditRecordRepository creditRecordRepository;
	@Autowired
	private EntCrProdEntityRepository entCrProdEntityRepository;
	@Autowired
	private CreditApplicationRepository creditApplicationRepository;
	@Autowired
	private CCBSericeImpl ccbSerice;
	@Autowired
	private CreditProductRepository creditProductRepository;
	@Autowired
	private FinanceDrawRepository financeDrawRepository;
	@Autowired
	private FinanceRepaymentRepository financeRepaymentRepository;
	@Autowired
	private FinanceDebitRepository financeDebitRepository;
	@Autowired
	private CreditInvoiceRepository creditInvoiceRepository;
	@Autowired
	private CashierOrderItemRepository cashierOrderItemRepository;
	@Autowired
	private PaymentOrderRepository paymentOrderRepository;
	@Autowired
	private PaymentPlanRepository paymentPlanRepository;
	@Autowired
	private PaymentRelationRepository paymentRelationRepository;
	@Autowired
	private FinanceAccountOperationRepository financeAccountOperationRepository;
	@Autowired
	private CreditUserServiceUtil creditUserServiceUtil;
	@Autowired
	private CreditRecordTimeRepository creditRecordTimeRepository;
	@Autowired
	private ProblemSericeImpl problemSericeImpl;
	@Autowired
	private OrderLoopService orderLoopService;
	@Resource(name="EMAIL")
	private INotificationService emailINotificationService;
	@Override
	public EntAccount getEntAccount(Long enId, String entType) {
		logger.info("### 筑材金融加载信息 start,tid={},entType={}",enId,entType);
		try {
			EntAccount entAccount = new EntAccount();
			EntAccountEntity entAccountEnt = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, enId, entType);

			if (entAccountEnt == null) {
				return null;
			}
			BeanUtils.copyProperties(entAccountEnt, entAccount);
			// 当位驳回状态时去查询最近的驳回原因 AccCheckStatus
			if (entAccountEnt.getCheckStatus().equals("REJECT") && entAccountEnt.getOperId() != null) {
				OperRecordEntity oper = operRecordRepository.findOne(entAccountEnt.getOperId());
				entAccount.setOperOpinion(oper.getReview());
			}
			// 获取最近委托书状态
			if (entAccount.getCertiId() != null) {
				EntCertificateEntity entCertificateEntity = entCertificateRepository.findOne(entAccount.getCertiId());
				entAccount.setCertiStatus(entCertificateEntity.getCertiStatus());
			}
			// 获取变更审核中 的委托书状态
			if (entAccount.getCertiChangeId() != null) {
				EntCertificateEntity entCertificateEntity = entCertificateRepository.findOne(entAccount.getCertiChangeId());
				entAccount.setCertiChangeStatus(entCertificateEntity.getCertiStatus());
			}
			return entAccount;
		} catch (Exception e) {
			logger.error("### 金融加载信息失败 errMsg={}", e);
			return null;
		}

	}

	/**
	 * 金融申请
	 */
	@Override
	public void saveEntAccount(EntAccount ea) {
		logger.info("### 金融信息申请和修改start,parm={}",ea.toString());
		try {
			// 判断金融信息id是否为空
			Long tid = ea.getTid();
			if (tid != null && tid != 0) {
				EntAccountEntity en = entAccountRepository.findByTid(tid);
				
				if(en.getEntType().equals(EntType.PURCHASER.toString())){
					EntCertificateEntity createCerti = createCerti(ea);
					en.setCertiImgId(ea.getCertiImgId());
					en.setCertiId(createCerti.getTid());
					en.setCertiChangeId(createCerti.getTid());
					en.setCertiChangeImgId(ea.getCertiImgId());
				}
				en.setCheckStatus(AccCheckStatus.APPROVEING.toString());
				en.setModifyDescription("驳回重新申请");
				// 判断防恶性申请是否勾选
				if (en.getAutoRejectStatus() != null && en.getAutoRejectStatus() == 1) {
					// 如果勾选了判断是否在自动驳回的时间内
					if (new Date().before(en.getAutoRejectTime())) {
						en.setCheckStatus(AccCheckStatus.REJECT.toString());
						logger.info("恶性申请,自动驳回");
						en.setModifyDescription("恶性申请,自动驳回");
					}
				}
				
				en.setModifyUser(ea.getUserId());
				entAccountRepository.saveAndFlush(en);
			} else {
				// 保存金融信息
				EntAccountEntity entAccountEntity = createEatAcc(ea);
				//判断供应商不用上传授权委托书
				if(entAccountEntity.getEntType().equals(EntType.PURCHASER.toString())){
					ea.setTid(entAccountEntity.getTid());
					// 保存委托书信息
					EntCertificateEntity entCertificateEntity = createCerti(ea);
					// 更新正在使用的委托书主键id
					entAccountEntity.setCertiId(entCertificateEntity.getTid());
					// 更新正在审核的委托书主键
					entAccountEntity.setCertiChangeId(entCertificateEntity.getTid());
				}
				entAccountRepository.saveAndFlush(entAccountEntity);
			}
		} catch (Exception e) {
			String problem = "金融账号申请和变更异常 金融id ="+ea.getTid()+",err="+e;
			emailINotificationService.notification(problem);
			logger.error("saveEntAccount的方法报错:error={}",e);
		}

	}

	//入驻金融时判断是否有核心企业推荐申请工商银行
	private void changeEntAccInfo(Long supAccId,Long supEntId){
		CreditProductEntity cpe = creditProductRepository.findByCrProdTypeAndStatusNot(CrProdType.ICBC_R_E_J.toString(), HelpConstant.Status.delete);
		if(cpe==null){
			return;
		}
		creditApplicationRepository.updateICBCSepInfo(supAccId, supEntId, cpe.getTid());
	}
	
	/**
	 * 创建金融信息
	 * 
	 * @param EntAccount
	 * @return EntAccountEntity
	 */
	private EntAccountEntity createEatAcc(EntAccount ea) {
		EntAccountEntity entAccountEntity = new EntAccountEntity();
		entAccountEntity.setApplyTime(new Date());
		entAccountEntity.setCheckStatus(AccCheckStatus.APPROVEING.toString());
		entAccountEntity.setEntType(ea.getEntType());
		entAccountEntity.setUnityOrgNum(ea.getUnityOrgNum());

		if (StringUtils.isEmpty(ea.getOrgNum()) && StringUtils.isNotEmpty(ea.getUnityOrgNum())) {
			if (ea.getUnityOrgNum().length() == 18) {
				entAccountEntity.setOrgNum(SqlResultUtil.getOrgNum(ea.getUnityOrgNum()));
			} else {
				entAccountEntity.setOrgNum(ea.getUnityOrgNum());
			}
		} else {
			if (ea.getOrgNum().length() == 18) {

				entAccountEntity.setOrgNum(SqlResultUtil.getOrgNum(ea.getOrgNum()));
			} else {
				entAccountEntity.setOrgNum(ea.getOrgNum());
			}
		}
		entAccountEntity.setModifyDescription("初始创建");
		entAccountEntity.setModifyUser(ea.getUserId());
		entAccountEntity.setCertiImgId(ea.getCertiImgId());
		entAccountEntity.setCertiChangeImgId(ea.getCertiImgId());
		entAccountEntity.setReadStatus(ea.getReadStatus());
		entAccountEntity.setEnterpriseId(ea.getEnterpriseId());
		entAccountEntity.setEnterpriseName(ea.getEnterpriseName());
		entAccountRepository.save(entAccountEntity);
		return entAccountEntity;
	}

	/**
	 * 创建委托书信息
	 * 
	 * @param EntAccount
	 * @return EntCertificateEntity
	 */
	private EntCertificateEntity createCerti(EntAccount ea) {
		EntCertificateEntity entCertificateEntity = new EntCertificateEntity();
		entCertificateEntity.setModifyDescription("初始创建");
		entCertificateEntity.setAccountId(ea.getTid());
		entCertificateEntity.setCreateUser(ea.getUserId());
		entCertificateEntity.setModifyUser(ea.getUserId());
		entCertificateEntity.setCertiStatus(ea.getCertiStatus());

		entCertificateEntity.setLinkeName(ea.getUserName());
		entCertificateEntity.setCertiImgId(ea.getCertiImgId());
		entCertificateEntity.setApplyTime(new Date());
		entCertificateRepository.save(entCertificateEntity);
		return entCertificateEntity;
	}

	/**
	 * 变更授权委托书
	 * 
	 * @param ea
	 */
	@Override
	public void changeCerti(EntAccount ea) {
		logger.info("### 变更授权委托书 changeCerti start");
		try {
			EntCertificateEntity entCertificateEntity = new EntCertificateEntity();
			// 委托书添加
			entCertificateEntity.setModifyDescription("变更授权书");
			entCertificateEntity.setAccountId(ea.getTid());
			entCertificateEntity.setCreateUser(ea.getUserId());
			entCertificateEntity.setModifyUser(ea.getUserId());
			entCertificateEntity.setCertiStatus(ea.getCertiChangeStatus());
			entCertificateEntity.setLinkeName(ea.getUserName());
			entCertificateEntity.setCertiImgId(ea.getCertiChangeImgId());
			entCertificateEntity.setApplyTime(new Date());
			entCertificateRepository.save(entCertificateEntity);

			// 根据id查询金融信息
			EntAccountEntity en = entAccountRepository.findByTid(ea.getTid());
			// 把金融信息表里的添加变更中的审核书
			en.setModifyDescription("变更授权书");
			en.setModifyUser(ea.getUserId());
			en.setCertiChangeId(entCertificateEntity.getTid());
			en.setCertiChangeImgId(ea.getCertiChangeImgId());
			entAccountRepository.saveAndFlush(en);
		} catch (Exception e) {
			logger.error("### 变更授权委托书异常 err={}",e);
		}

	}

	// 查询待支取和待还款的融资记录条数
	private CreditRecordForm findCountByAmount(CreditRecord cr) {
		CreditRecordForm crf = new CreditRecordForm();
		// 融资异常状态正常NORMAL集合
		List<String> unusualNormalList = new ArrayList<String>();
		unusualNormalList.add("NORMAL");
		unusualNormalList.add("WAIT_CONFIRM_CANCEL");
		unusualNormalList.add("CONTRACT_REJECT");
		unusualNormalList.add("CONFIRM_ZZW_CANCEL");
		unusualNormalList.add("NETWORK_ERROR");
		// 融资异常状态集合
		List<String> unusualList = new ArrayList<String>();
		unusualList.add("WAIT_CONFIRM_CANCEL");
		unusualList.add("CONTRACT_REJECT");
		unusualList.add("CONFIRM_ZZW_CANCEL");
		unusualList.add("NETWORK_ERROR");

		// 待支取条数
		Integer drawAmountCount = 0;
		// 待还款状态集合
		List<String> drawStatuList = new ArrayList<String>();
		drawStatuList.add("PENDING_WITHDRAWAL");

		// 采购商审核条数
		Integer waitConfirmPurCount = 0;
		// 采购商审核状态集合
		List<String> waitConfirmPurList = new ArrayList<String>();
		waitConfirmPurList.add("WAIT_CONFIRM");
		waitConfirmPurList.add("WAIT_CONFIRM_ZZW");
		waitConfirmPurList.add("WAIT_PAY");

		// 待还款条数
		Integer repaymentAmountCount = 0;
		// 待还款状态集合
		List<String> repaymentStatuList = new ArrayList<String>();
		repaymentStatuList.add("REPAYMENT");

		// 待签合同
		Integer signingContractCount = 0;
		// 待签合同状态集合
		List<String> signingStatuList = new ArrayList<String>();
		signingStatuList.add("SUBSTITUTE_CONTRACT");

		// 已还款
		Integer repaymentedCount = 0;
		// 已还款状态集合
		List<String> repaymentedStatuList = new ArrayList<String>();
		repaymentedStatuList.add("REPAYMENTS");
		// 已还款支付状态集合

		// 违约/异议
		Integer breakContractCount = 0;
		// 违约/异议状态集合
		List<String> breakStatuList = new ArrayList<String>();
		breakStatuList.add("BREACH_OF_CONTRACT");

		// 融资失败
		Integer failedFinanceCount = 0;
		// 融资失败状态集合
		List<String> failedStatuList = new ArrayList<String>();
		failedStatuList.add("WAIT_SUBMIT");

		// 融资确认
		Integer waitConfirmCount = 0;
		// 融资确认状态集合
		List<String> waitConfirmStatuList = new ArrayList<String>();
		waitConfirmStatuList.add("WAIT_CONFIRM");
		waitConfirmStatuList.add("WAIT_CONFIRM_ZZW");

		// 待支付条数
		Integer waitPayCount = 0;
		// 待支付状态集合
		List<String> waitPayStatuList = new ArrayList<String>();
		waitPayStatuList.add("WAIT_PAY");
		// 待支付状态集合
		List<String> orderStatusList = new ArrayList<String>();
		orderStatusList.add("02");
		orderStatusList.add("05");

		// 采购商用户权限
		List<Long> purUserList = new ArrayList<Long>();
		// 供应商用户权限
		List<Long> supUserList = new ArrayList<Long>();

		try {
			if (cr.getEntType().equals(EntType.PURCHASER.toString())) {
				EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getOriginatorEnterpriseId(),
						cr.getEntType());
				cr.setOriginator(entAccountEntity.getTid());

				purUserList = cr.getUserIdList();
				// 供应商的加入默认查不到的0
				supUserList.add(Long.valueOf(0));
			} else if (cr.getEntType().equals(EntType.SUPPLIER.toString())) {
				EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getParticipatorEnterpriseId(),
						cr.getEntType());
				cr.setParticipator(entAccountEntity.getTid());

				supUserList = cr.getUserIdList();
				// 采购商加入默认查不到的0
				purUserList.add(Long.valueOf(0));
			}
			// 待支取
			drawAmountCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), drawStatuList, purUserList, supUserList,
					unusualNormalList);
			// 待签合同
			signingContractCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), signingStatuList, purUserList,
					supUserList, unusualNormalList);
			// 已还款
			repaymentedCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), repaymentedStatuList, purUserList,
					supUserList, unusualNormalList);
			// 融资失败集合
			failedFinanceCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), failedStatuList, purUserList,
					supUserList, unusualList);
			// 违约
			breakContractCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), breakStatuList, purUserList,
					supUserList, unusualNormalList);
			// 待还款
			repaymentAmountCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), repaymentStatuList, purUserList,
					supUserList, unusualNormalList);
			// 待确认
			waitConfirmCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), waitConfirmStatuList, purUserList,
					supUserList, unusualNormalList);
			// 采购商红标里的待审核
			waitConfirmPurCount = creditRecordRepository.findLabelCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), waitConfirmPurList, purUserList,
					supUserList, unusualNormalList);
			// 待支付融资单条数
			waitPayCount = creditRecordRepository.findWaitPayCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), waitPayStatuList, purUserList,
					supUserList, unusualNormalList, orderStatusList);

		} catch (Exception e) {
			logger.error("findCountByAmount的错误: errMsg={}", e);
			crf.setWithdrawalCount(drawAmountCount == null ? Integer.valueOf(0) : drawAmountCount);
			crf.setRepaymentCount(repaymentAmountCount == null ? Integer.valueOf(0) : repaymentAmountCount);
			crf.setSigningContractCount(signingContractCount == null ? Integer.valueOf(0) : signingContractCount);
			crf.setRepaymentedCount(repaymentedCount == null ? Integer.valueOf(0) : repaymentedCount);
			crf.setBreakContractCount(breakContractCount == null ? Integer.valueOf(0) : breakContractCount);
			crf.setFailedFinanceCount(failedFinanceCount == null ? Integer.valueOf(0) : failedFinanceCount);
			crf.setWaitConfirmCount(waitConfirmCount == null ? Integer.valueOf(0) : waitConfirmCount);
			crf.setWaitConfirmPurCount(waitConfirmPurCount == null ? Integer.valueOf(0) : waitConfirmPurCount);
			crf.setWaitPayCount(waitPayCount == null ? Integer.valueOf(0) : waitPayCount);
			return crf;
		}
		crf.setWithdrawalCount(drawAmountCount == null ? Integer.valueOf(0) : drawAmountCount);
		crf.setRepaymentCount(repaymentAmountCount == null ? Integer.valueOf(0) : repaymentAmountCount);
		crf.setSigningContractCount(signingContractCount == null ? Integer.valueOf(0) : signingContractCount);
		crf.setRepaymentedCount(repaymentedCount == null ? Integer.valueOf(0) : repaymentedCount);
		crf.setBreakContractCount(breakContractCount == null ? Integer.valueOf(0) : breakContractCount);
		crf.setFailedFinanceCount(failedFinanceCount == null ? Integer.valueOf(0) : failedFinanceCount);
		crf.setWaitConfirmCount(waitConfirmCount == null ? Integer.valueOf(0) : waitConfirmCount);
		crf.setWaitConfirmPurCount(waitConfirmPurCount == null ? Integer.valueOf(0) : waitConfirmPurCount);
		crf.setWaitPayCount(waitPayCount == null ? Integer.valueOf(0) : waitPayCount);
		return crf;
	}

	// 处理综合搜索条件
	private CreditRecord dealSeachParm(CreditRecord cr) {
		if ("contractNum".equals(cr.getSearchStatus())) {
			cr.setContractNum(cr.getSearchParm());
		} else if ("paymentNum".equals(cr.getSearchStatus())) {
			cr.setPaymentNum(cr.getSearchParm());
		} else if ("recordNo".equals(cr.getSearchStatus())) {
			cr.setRecordNo(cr.getSearchParm());
		} else if ("supEntName".equals(cr.getSearchStatus())) {
			cr.setSupEnteriseName(cr.getSearchParm());
		} else if ("purEntName".equals(cr.getSearchStatus())) {
			cr.setPurEnteriseName(cr.getSearchParm());
		}
		return cr;

	}

	/**
	 * 查询融资记录列表信息(带分页) TODO
	 */
	public CreditRecordForm findCreditRecordList(CreditRecord cr, Pageable pa) {
		logger.info("### 查询融资记录 start cr={}",cr.toString());
		Page<CreditRecord> page = null;
		CreditRecordForm creditRecordForm = new CreditRecordForm();
		try {
			// 采购商用户权限
			List<Long> purUserList = new ArrayList<Long>();
			// 供应商用户权限
			List<Long> supUserList = new ArrayList<Long>();

			// 采购商部门权限
			List<Long> purDepartmentList = new ArrayList<Long>();
			// 供应商部门权限
			List<Long> supDepartmentList = new ArrayList<Long>();
			// 融资记录集合
			List<Object[]> ogjList = new ArrayList<Object[]>();

			// 待付款总金额
			BigDecimal waitPayAllAmt = BigDecimal.ZERO;
			// 返回融资状态集合

			// 融资记录条数
			Integer recordCount = 0;
			cr = dealSeachParm(cr);
			if (cr.getEntType().equals(EntType.PURCHASER.toString())) {

				EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getOriginatorEnterpriseId(),
						cr.getEntType());
				cr.setOriginator(entAccountEntity.getTid());

				purUserList = cr.getUserIdList();
				// 供应商的加入默认查不到的0
				supUserList.add(Long.valueOf(0));

				purDepartmentList = cr.getDepartmentIdList();
				supDepartmentList.add(0L);
			} else if (cr.getEntType().equals(EntType.SUPPLIER.toString())) {

				EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getParticipatorEnterpriseId(),
						cr.getEntType());
				cr.setParticipator(entAccountEntity.getTid());

				supUserList = cr.getUserIdList();
				// 采购商加入默认查不到的0
				purUserList.add(Long.valueOf(0));

				supDepartmentList = cr.getDepartmentIdList();
				purDepartmentList.add(0L);
			}
			// 订单状态
			String affLineOrderStatus = null;
			// 订单状态
			String waitPayOrderStatus = null;
			// 融资状态集合
			List<String> statusList = new ArrayList<String>();
			// 融资异常状态集合
			List<String> unusualList = new ArrayList<String>();
			unusualList.add("NORMAL");
			unusualList.add("NETWORK_ERROR");
			unusualList.add("CONFIRM_ZZW_CANCEL");
			unusualList.add("WAIT_CONFIRM_CANCEL");
			unusualList.add("CONTRACT_REJECT");
			if ("REFUSE_CANCEL".equals(cr.getCreditStatus())) {
				// 融资失败
				statusList.add("WAIT_SUBMIT");

				unusualList.remove(0);
			} else if ("WAIT_CONFIRM_SUP".equals(cr.getCreditStatus())) {
				// 待确认
				statusList.add("WAIT_CONFIRM");
				statusList.add("WAIT_CONFIRM_ZZW");

				// 待支付
			} else if ("WAIT_PAY".equals(cr.getCreditStatus())) {
				// 待确认
				statusList.add("WAIT_PAY");
				statusList.add("SUMBIT_TO_BANK");
				// 查询待付款的
				waitPayAllAmt = getWaitPayAllAmt(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), statusList, purUserList, supUserList, purDepartmentList,
						supDepartmentList, cr.getProjectTid(), cr.getCrProdId(), cr.getRecordNo(), cr.getContractNum(), cr.getPaymentNum(), cr.getSupEnteriseName(),
						cr.getPurEnteriseName(), unusualList);
				// 采购商待审核tab标签
			} else if ("WAIT_PAY_SUP".equals(cr.getCreditStatus())) {
				// 待支付
				statusList.add("WAIT_PAY");
				waitPayOrderStatus = "05";
				// 查询待付款的
				waitPayAllAmt = getWaitPayAllAmt(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), statusList, purUserList, supUserList, purDepartmentList,
						supDepartmentList, cr.getProjectTid(), cr.getCrProdId(), cr.getRecordNo(), cr.getContractNum(), cr.getPaymentNum(), cr.getSupEnteriseName(),
						cr.getPurEnteriseName(), unusualList);
				// 采购商待审核tab标签
			} else if ("WAIT_CONFIRM_PUR".equals(cr.getCreditStatus())) {
				statusList.add("WAIT_CONFIRM");
				statusList.add("WAIT_CONFIRM_ZZW");
				statusList.add("WAIT_PAY");
				statusList.add("SUMBIT_TO_BANK");
			} else if ("OFFLINE_PAY".equals(cr.getCreditStatus())) {
				statusList.add("WAIT_PAY");
				affLineOrderStatus = "05";
			} else {
				// 其他
				statusList.add(cr.getCreditStatus());
			}

			Sort sort = new Sort(Sort.Direction.valueOf(cr.getDataSort()), "loan_date");
			Pageable pageable = new PageRequest(cr.getNextPage(), cr.getPageSize(), sort);

			ogjList = creditRecordRepository.findCreditRecordList(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), statusList, purUserList, supUserList,
					purDepartmentList, supDepartmentList, cr.getProjectTid(), cr.getCrProdId(), cr.getRecordNo(), cr.getContractNum(), cr.getPaymentNum(), cr.getSupEnteriseName(),
					cr.getPurEnteriseName(), unusualList, affLineOrderStatus, waitPayOrderStatus, pageable);

			// 融资记录条数
			recordCount = creditRecordRepository.findCreditRecordCount(HelpConstant.Status.delete, cr.getOriginator(), cr.getParticipator(), statusList, purUserList, supUserList,
					purDepartmentList, supDepartmentList, cr.getProjectTid(), cr.getCrProdId(), cr.getRecordNo(), cr.getContractNum(), cr.getPaymentNum(), cr.getSupEnteriseName(),
					cr.getPurEnteriseName(), unusualList, affLineOrderStatus, waitPayOrderStatus);
			List<CreditRecord> crList = new ArrayList<CreditRecord>();
			if (!ogjList.isEmpty()) {
				for (Object[] obj : ogjList) {
					CreditRecord creditRecord = new CreditRecord();
					// 主键id
					creditRecord.setTid(SqlResultUtil.getSqlResultLong(obj[11]));
					// 合同id
					creditRecord.setContractNum(SqlResultUtil.getSqlResultString(obj[0]));
					// 付款单号
					creditRecord.setPaymentNum(SqlResultUtil.getSqlResultString(obj[1]));
					// 融资编号
					creditRecord.setRecordNo(SqlResultUtil.getSqlResultString(obj[2]));
					// 融资银行
					creditRecord.setCrProdBankName(SqlResultUtil.getSqlResultString(obj[3]));
					// 采购商商家名称
					creditRecord.setPurEnteriseName(SqlResultUtil.getSqlResultString(obj[4]));
					// 供应商商家名称
					creditRecord.setSupEnteriseName(SqlResultUtil.getSqlResultString(obj[5]));
					// 融资金额
					BigDecimal creditAmount = SqlResultUtil.getSqlResultBigDecimal(obj[6]);
					creditRecord.setCreditAmount(creditAmount == null ? BigDecimal.ZERO : creditAmount);
					// 账款金额
					BigDecimal creditGetAmount = SqlResultUtil.getSqlResultBigDecimal(obj[7]);
					creditRecord.setCreditGetAmount(creditGetAmount == null ? BigDecimal.ZERO : creditGetAmount);
					Date loanDate = SqlResultUtil.getSqlResultDate2(SqlResultUtil.getSqlResultString(obj[8]));
					// 账款到期日
					creditRecord.setLoanDate(loanDate);
					
					// 计算账期
					Integer dateTian = TimeUtils.dateTian(loanDate, new Date());
					creditRecord.setCreditPeriod(dateTian);
					// 还款到期日
					creditRecord.setProjectTid(SqlResultUtil.getSqlResultLong(obj[9]));
					// 融资状态
					creditRecord.setCreditStatus(SqlResultUtil.getSqlResultString(obj[10]));
					// 采购商已还款金额
					BigDecimal purBd = SqlResultUtil.getSqlResultBigDecimal(obj[12]);
					creditRecord.setPurRepaymentAmount(purBd);
					// 供应商已还款金额
					BigDecimal supBd = SqlResultUtil.getSqlResultBigDecimal(obj[13]);
					creditRecord.setSupRepaymentAmount(supBd);
					// 计划付款id
					creditRecord.setPaymentId(SqlResultUtil.getSqlResultLong(obj[14]));
					// 支取金额
					BigDecimal bd = SqlResultUtil.getSqlResultBigDecimal(obj[15]) == null ? BigDecimal.ZERO : SqlResultUtil.getSqlResultBigDecimal(obj[15]);
					creditRecord.setDrawAmount(bd);
					// 支取金额减去总的已还款金额
					BigDecimal wd = bd.subtract(SqlResultUtil.getSqlResultBigDecimal(obj[16]) == null ? BigDecimal.ZERO : SqlResultUtil.getSqlResultBigDecimal(obj[16]));
					wd = wd.setScale(2, BigDecimal.ROUND_HALF_UP);
					// 总还款金额
					creditRecord.setRepaymentAmount(SqlResultUtil.getSqlResultBigDecimal(obj[16]) == null ? BigDecimal.ZERO : SqlResultUtil.getSqlResultBigDecimal(obj[16]));
					creditRecord.setDrawRate(SqlResultUtil.getSqlResultBigDecimal(obj[17]));
					// 最近筑材网驳回原因
					creditRecord.setRejectReason(SqlResultUtil.getSqlResultString(obj[18]));

					// 融资到期日
					creditRecord.setLoanDateCcb(SqlResultUtil.getSqlResultDate2(SqlResultUtil.getSqlResultString(obj[19])));

					//距离还款天数
					if(creditRecord.getLoanDateCcb()!=null){
						Integer fromRepaymentDate = TimeUtils.dateTian(creditRecord.getLoanDateCcb(), new Date());
						creditRecord.setFromRepaymentDate(fromRepaymentDate);
					}
					creditRecord.setProjectName(SqlResultUtil.getSqlResultString(obj[21]));

					creditRecord.setCreditUnusualStatus(SqlResultUtil.getSqlResultString(obj[22]));
					// 融资利率
					BigDecimal crProdRate = SqlResultUtil.getSqlResultBigDecimal(obj[26]);
					cr.setCreditPeriod(dateTian);
					BigDecimal orderAmt = SqlResultUtil.getOrderAmt(creditRecord.getCreditGetAmount(), dateTian, crProdRate).setScale(2, BigDecimal.ROUND_HALF_UP);
					creditRecord.setOrderAmt(orderAmt);

					// 支付明细的支付状态
					creditRecord.setPayStatus(SqlResultUtil.getSqlResultString(obj[25]));

					crList.add(creditRecord);
				}
			}

			page = new MyPage<CreditRecord>(cr.getNextPage(), cr.getPageSize(), crList, recordCount == null ? 0 : recordCount);
			creditRecordForm.setCreditRecordPage(page);
			creditRecordForm.setWaitPayAllAmt(waitPayAllAmt);
		} catch (Exception e) {
			logger.error("### 查询融资记录发生异常errMsg={}", e);
			return creditRecordForm;
		}
		return creditRecordForm;
	}

	// 获取待付款总金额
	private BigDecimal getWaitPayAllAmt(int delete, Long originator, Long participator, List<String> statusList, List<Long> purUserList, List<Long> supUserList,
			List<Long> purDepartmentList, List<Long> supDepartmentList, Long projectTid, Long crProdId, String recordNo, String contractNum, String paymentNum,
			String supEnteriseName, String purEnteriseName, List<String> unusualList) {
		BigDecimal waitPayAmt = BigDecimal.ZERO;
		List<Object[]> findWaitPayAllAmtList = creditRecordRepository.findWaitPayAllAmtList(delete, originator, participator, statusList, purUserList, supUserList,
				purDepartmentList, supDepartmentList, projectTid, crProdId, recordNo, contractNum, paymentNum, supEnteriseName, purEnteriseName, unusualList);

		if (CollectionUtils.isNotEmpty(findWaitPayAllAmtList)) {
			for (Object[] obj : findWaitPayAllAmtList) {
				Date loanDate = SqlResultUtil.getSqlResultDate2(SqlResultUtil.getSqlResultString(obj[3]));
				// 计算账期
				Integer dateTian = TimeUtils.dateTian(loanDate, new Date());
				BigDecimal rate = SqlResultUtil.getSqlResultBigDecimal(obj[4]);
				/** 算服务费 入参：融资金额、账期、费率 */
				BigDecimal orderAmt = SqlResultUtil.getOrderAmt(SqlResultUtil.getSqlResultBigDecimal(obj[0]), dateTian, rate).setScale(2, BigDecimal.ROUND_HALF_UP);
				waitPayAmt = waitPayAmt.add(orderAmt);
			}
		}

		return waitPayAmt;

	}

	/**
	 * 我的筑材金融加载信息(不用权限控制) TODO
	 */
	@Override
	public EntAccount entAccountLoading(EntAccount ea) {
		logger.info("我的筑材金融加载信息start,parm={}", ea);
		EntAccount entAccount = new EntAccount();
		// 采购商金融id
		Long purId = null;
		// 供应商金融id
		Long supId = null;
		// 总的融资余额
		BigDecimal allTypeAmount = BigDecimal.ZERO;
		// 已开通的金融机构的融资信息集合
		List<CreditProduct> openedCrPrTypeList = new ArrayList<CreditProduct>();
		try {
			// 根据userid查询筑材金融信息
			EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, ea.getEnterpriseId(), ea.getEntType());
			logger.debug("商家类型企业id={},查询出金融信息EntAccountEntity={}", entAccountEntity);

			// 采购商用户权限
			List<Long> purUserList = new ArrayList<Long>();
			// 供应商用户权限
			List<Long> supUserList = new ArrayList<Long>();
			// 查询融资金额状态集合
			List<String> totalStatusList = new ArrayList<String>();
			totalStatusList.add("PENDING_WITHDRAWAL");
			totalStatusList.add("REPAYMENT");
			totalStatusList.add("REPAYMENTS");
			// 待采购商审核的状态集合
			List<String> waitApproveStatusList = new ArrayList<String>();
			waitApproveStatusList.add("BANK_AUDIT");
			waitApproveStatusList.add("ICBC_WAIT_CONFIRM_PUR");
			// 待供应商提交资料的状态集合
			List<String> waitSubmitStatusList = new ArrayList<String>();
			waitSubmitStatusList.add("ICBC_HISTROY_INFO");
			waitSubmitStatusList.add("ICBC_REJECT_PUR");

			if (entAccountEntity != null) {
				BeanUtils.copyProperties(entAccountEntity, entAccount);
				if (entAccount.getEntType().equals(EntType.PURCHASER.toString())) {
					purUserList.add(Long.valueOf(0));
					// 供应商的加入默认查不到的0
					supUserList.add(Long.valueOf(0));
					purId = entAccountEntity.getTid();
				} else if (entAccount.getEntType().equals(EntType.SUPPLIER.toString())) {
					// 采购商的加入默认查不到的0
					purUserList.add(Long.valueOf(0));
					// 供应商的加入默认查不到的0
					supUserList.add(Long.valueOf(0));
					supId = entAccountEntity.getTid();
				}
				// 获取此用户的所有贷款机构的所有融资金额
				allTypeAmount = creditRecordRepository.findBalanceAmt(HelpConstant.Status.delete, purId, supId, null, totalStatusList);
			}

			// 查询银行金融机构服务的信息
			List<CreditProductEntity> findCreditProdList = creditProductRepository.findByStatusNot(HelpConstant.Status.delete);
			for (CreditProductEntity creditProductEntity : findCreditProdList) {
				CreditProduct creditProduct = new CreditProduct();
				BeanUtils.copyProperties(creditProductEntity, creditProduct);
				creditProduct.setEntType(ea.getEntType());
				// 判断此银行金融产品是否开通
				if (entAccountEntity != null) {
					EntCrProdEntity cr = entCrProdEntityRepository.findZhucaiProdRecord(entAccountEntity.getTid(), HelpConstant.Status.delete, creditProductEntity.getTid(),
							ZhuCaiProdType.ZHU_CAI_B_TONG.toString(), EnCrStatus.PASS.toString());
					if (cr != null) {
						creditProduct.setCrProdstatus("PASS");
					} else {
						creditProduct.setCrProdstatus("FAIL");
					}
					// 此用户此机构的所有的融资金额
					BigDecimal creditAmount = creditRecordRepository.findTotalAmount(HelpConstant.Status.delete, purId, supId, totalStatusList, creditProductEntity.getTid());
					creditProduct.setCreditAmount(creditAmount == null ? BigDecimal.ZERO : creditAmount);
					// 根据银行查询合作的商家
					Integer findBusCoopCount = creditRecordRepository.findBusCoopCount(HelpConstant.Status.delete, purId, supId, CrAprovalStatus.BANK_SUCCESS.toString(),
							creditProductEntity.getTid());
					creditProduct.setCooperativeCount(findBusCoopCount == null ? Integer.valueOf(0) : findBusCoopCount);
					// 根据银行查询融资余额
					BigDecimal balanceFinancingAmount = creditRecordRepository.findBalanceAmt(HelpConstant.Status.delete, purId, supId, creditProductEntity.getTid(),
							totalStatusList);
					creditProduct.setBalanceFinancingAmount(balanceFinancingAmount == null ? BigDecimal.ZERO : balanceFinancingAmount);
					if (entAccount.getEntType().equals(EntType.PURCHASER.toString())) {
						// 查询建设银行查询待审核的合作供应商
						Integer waitApprovebSupCoopCount = creditRecordRepository.findAppBusCoopCount(HelpConstant.Status.delete, purId, supId,
								waitApproveStatusList, creditProductEntity.getTid());
						creditProduct.setWaitApproveSupCount(waitApprovebSupCoopCount == null ? Integer.valueOf(0) : waitApprovebSupCoopCount);
					} else if (entAccount.getEntType().equals(EntType.SUPPLIER.toString())) {
						// 查询待供应商操作的
						Integer icbcHistroyCount = creditRecordRepository.findAppBusCoopCount(HelpConstant.Status.delete, purId, supId,
								waitSubmitStatusList, creditProductEntity.getTid());
						creditProduct.setIcbcHistroyCount(icbcHistroyCount == null ? Integer.valueOf(0) : icbcHistroyCount);
					}

				} else {
					creditProduct.setCreditAmount(BigDecimal.ZERO);
					creditProduct.setCrProdstatus("FAIL");
					creditProduct.setCooperativeCount(Integer.valueOf(0));
					creditProduct.setBalanceFinancingAmount(BigDecimal.ZERO);
					creditProduct.setWaitApproveSupCount(Integer.valueOf(0));
				}

				openedCrPrTypeList.add(creditProduct);

			}
			// 查询融资机构
		} catch (Exception e) {
			logger.error("### 我的筑材金融加载信息发生异常 errMsg={}", e);
			return null;
		}

		entAccount.setCreditAmounts(allTypeAmount == null ? BigDecimal.ZERO : allTypeAmount);
		entAccount.setOpenedCrPrTypeList(openedCrPrTypeList);
		return entAccount;
	}

	/**
	 * 采购商审核供应商页面加载信息
	 */
	@Override
	public CreditApplication findCreditApplicationInfo(CreditApplication ca) {

		logger.info("### 采购商审核供应商页面加载信息 ca={}", ca.toString());
		if(ca.getTid() == null){
			return ca;
		}
		ca = creditUserServiceUtil.getCreditApplicationById(ca.getTid());
		// 查询审核记录
		List<OperRecordEntity> operRecordEntList = operRecordRepository.findByOutIdAndStatusNotAndOperTypeOrderByOperTimeDesc(ca.getTid(), HelpConstant.Status.delete,
				OperType.PUR_APP_SUP.toString());
		List<OperRecord> operRecordList = new ArrayList<OperRecord>();
		if (operRecordEntList != null && operRecordEntList.size() > 0) {
			for (OperRecordEntity obj : operRecordEntList) {
				OperRecord operRecord = new OperRecord();
				BeanUtils.copyProperties(obj, operRecord);
				if (operRecord.getOperAmount() != null) {
					BigDecimal multiply = operRecord.getOperAmount().divide(new BigDecimal(1000));
					operRecord.setOperAmount(multiply);
				}
				operRecordList.add(operRecord);
			}
		}
		ca.setOperRecordList(operRecordList);
		
		//查询最近的一条操作记录
		if(ca.getOperRecordId() != null){
			OperRecordEntity findOne = operRecordRepository.findOne(ca.getOperRecordId());
			ca.setRejectRemark(findOne.getReview());
		}
		return ca;
	}

	/**
	 * 审核供应商
	 * 
	 * @param CreditApplication
	 * @return Integer
	 */
	@Override
	public Integer approveSupCredit(CreditApplication ca) {
		logger.info("### 采购商审核供应商(approveSupCredit) start，data = {} ", ca.toString());
		try {
			CreditApplicationEntity creditApplicationEntity = creditApplicationRepository.findOne(ca.getTid());
			if (creditApplicationEntity.getCrAprovalStatus().equals(CrAprovalStatus.DATA_REVIEW.toString())
					|| creditApplicationEntity.getCrAprovalStatus().equals(CrAprovalStatus.PUR_REJECT.toString())) {
				logger.warn("### 采购商审核供应商(approveSupCredit) 此数据已被审核过,date = {}", creditApplicationEntity.getCrAprovalStatus());
				return 0;
			}
			// 插入审核记录
			OperRecordEntity operRecord = new OperRecordEntity();
			operRecord.setBizKey(ca.getCrAprovalStatus());
			operRecord.setModifyDescription("采购商审核供应商");
			if (ca.getCrLineOfCredit() != null) {
				operRecord.setOperAmount(BigDecimal.valueOf(ca.getCrLineOfCredit()).multiply(BigDecimal.valueOf(1000)));
			}
			operRecord.setOperator(ca.getUserId());
			operRecord.setOperatorName(ca.getLinkPerson());
			operRecord.setOperTime(new Date());
			operRecord.setOperType(OperType.PUR_APP_SUP.toString());
			operRecord.setOutId(ca.getTid());
			operRecord.setDisputeCount(ca.getDisputeCount());
			operRecord.setFluctStabilization(ca.getFluctStabilization());
			operRecord.setTradingYears(ca.getTradingYears());
			operRecord.setTransactionActivity(ca.getTransactionActivity());
			operRecord.setTransactionEvaluate(ca.getTransactionEvaluate());
			if (ca.getCrAprovalStatus() != null) {
				operRecord.setResult(EnumHelper.getDescribe(CrAprovalStatus.valueOf(ca.getCrAprovalStatus())));
			} else {
				operRecord.setResult(ca.getCrAprovalStatus());
			}
			operRecord.setReview(ca.getCrSupEvaluate());

			// 更新审核
			// 采购商评价
			creditApplicationEntity.setCrSupEvaluate(ca.getCrSupEvaluate());
			// 审核状态
			creditApplicationEntity.setCrAprovalStatus(ca.getCrAprovalStatus());
			// 授信额度
			creditApplicationEntity.setCrLineOfCredit(ca.getCrLineOfCredit());
			creditApplicationEntity.setOperRecordId(operRecord.getTid());
			// 纠纷次数
			creditApplicationEntity.setDisputeCount(ca.getDisputeCount());
			// 交易活跃度
			creditApplicationEntity.setTransactionActivity(ca.getTransactionActivity());
			// 交易评价
			creditApplicationEntity.setTransactionEvaluate(ca.getTransactionEvaluate());
			// 上下游稳定性
			creditApplicationEntity.setFluctStabilization(ca.getFluctStabilization());
			creditApplicationEntity.setTradingYears(ca.getTradingYears());
			BeanUtils.copyProperties(creditApplicationEntity, ca);
			// 当采购商审核通过调用建行接口,传递信息
			if (ca.getCrAprovalStatus().equals(CrAprovalStatus.PUR_CONFIRM_SUCCESS.toString())) {
				ccbSerice.purApproveToCCb(ca);
			}
			creditApplicationRepository.saveAndFlush(creditApplicationEntity);
			
			BeanUtils.copyProperties(creditApplicationEntity, ca);
			operRecordRepository.save(operRecord);

		} catch (SubmitCcbException e) {
			logger.error("### 审核供应商 提交建行失败 errMsg={}", e);
			/**
			 * 问题记录
			 */
			String problem = "### 建行5502出错，tid="+ca.getTid()+",异常 errMsg="+e;
			problemSericeImpl.setProblem(problem,"6W5502");
			emailINotificationService.notification("### 建行提交5502异常 tid="+ca.getTid()+",err="+e);
			return 2;
		} catch (IOException e) {
			logger.error("### 审核供应商 建行接口连接失败 errMsg={}", e);
			/**
			 * 问题记录
			 */
			String problem = "### 建行5502出错，tid="+ca.getTid()+"异常 errMsg="+e;
			problemSericeImpl.setProblem(problem,"6W5502");
			emailINotificationService.notification("### 建行提交5502异常 tid="+ca.getTid()+",err="+e);
			return 2;
		}catch (Exception e) {
			emailINotificationService.notification("### 建行提交5502异常tid="+ca.getTid()+",err="+e);
			logger.error("### 审核供应商 发生异常 errMsg={}" ,e);
			return 0;
		}

		return 1;
	}


	/**
	 * 加载融资跟踪
	 * 
	 * @date 2017年12月4日 @user hsg
	 */
	@Override
	public CreditRecord loadIngFinanceTrack(CreditRecord cr) {
		logger.debug("### 加载融资跟踪start data={}",cr.toString());
		try {
			CreditRecordEntrity creditRecordEntrity = creditRecordRepository.findByStatusNotAndContractId(HelpConstant.Status.delete, cr.getContractNum());
			if (creditRecordEntrity != null) {
				BeanUtils.copyProperties(creditRecordEntrity, cr);
			} 
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return cr;
	}

	/**
	 * 判断采购商和供应商筑保通是否合作
	 * 
	 * @date 2017年12月5日 @user hsg
	 */
	@Override
	public Boolean findCreditApplication(CreditRecord cr) {
		try {
			EntAccountEntity purEnt = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getOriginatorEnterpriseId(),
					EntType.PURCHASER.toString());
			EntAccountEntity supEnt = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getParticipatorEnterpriseId(),
					EntType.SUPPLIER.toString());

			List<CreditApplicationEntity> findCreditAppBySupIdAndPurIdAndOver = creditApplicationRepository.findCreditAppBySupIdAndPurIdAndOver(HelpConstant.Status.delete,
					purEnt.getTid(), supEnt.getTid());
			//判断此供应商的筑保通状态是否正常
			List<EntCrProdEntity> ecpe = entCrProdEntityRepository.findByAccIdList(supEnt.getTid(), HelpConstant.Status.delete, ZhuCaiProdType.ZHU_CAI_B_TONG.toString(),
					EnCrStatus.PASS.toString());
			
			if (CollectionUtils.isNotEmpty(findCreditAppBySupIdAndPurIdAndOver) && CollectionUtils.isNotEmpty(ecpe)) {
				return true;
			};
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		return false;
	}


	/**
	 * @date 2017年12月5日 @user hsg
	 */
	@Override
	public CreditRecord findCreditRecordByConNum(String contract_num) {
		CreditRecord cr = new CreditRecord();
		try {
			CreditRecordEntrity cre = creditRecordRepository.findByStatusNotAndContractNumAndCreditStatusNot(HelpConstant.Status.delete, contract_num,
					CreditStatus.REFUSE_CANCEL.toString());
			BeanUtils.copyProperties(cre, cr);
			return cr;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}

	}

	/**
	 * 获取贷款机构类型
	 * 
	 * @date 2017年12月7日 @user hsg
	 */
	@Override
	public CreditProduct findCreditProductByProdType(CreditProduct cp) {
		StringBuilder str = new StringBuilder();
		try {
			CreditProductEntity creditProductEntity = creditProductRepository.findByCrProdTypeAndStatusNot(cp.getCrProdType(), HelpConstant.Status.delete);
			str.append("根据贷款机构类型查询贷款机构信息，参数CrProdType：" + cp.getCrProdType() + ",");
			BeanUtils.copyProperties(creditProductEntity, cp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return cp;
		} finally {
			logger.info(str.toString());
		}
		return cp;
	}

	/**
	 * 根据融资tid查询融资跟踪记录
	 * 
	 * @date 2017年12月7日 @user hsg
	 */
	@Override
	public CreditRecord findCreditRecordByTid(Long tid) {
		logger.info("### 根据融资tid查询融资跟踪记录（findCreditRecordByTid）start,tid={}", tid);
		CreditRecord findCreditRecordInfo = null;
		try {
			findCreditRecordInfo = creditUserServiceUtil.findCreditRecordInfo(null, tid);
		} catch (Exception e) {
			// TODO: handle exception
			logger.info("### 根据融资tid查询融资跟踪记录（findCreditRecordByTid）发生异常 errMSg={},tid={}", e, tid);
		}
		return findCreditRecordInfo;

	}

	/**
	 * 根据企业id查询金融信息
	 * 
	 * @date 2017年12月12日 @user hsg
	 */
	@Override
	public EntAccount getEntAccountByEntId(Long entId, String entType) {
		logger.info("### 根据企业id查询金融信息 entId={}，entType={}",entId,entType);
		EntAccount ea = new EntAccount();
		try {
			EntAccountEntity eae = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, entId, entType);
			if (eae != null) {
				BeanUtils.copyProperties(eae, ea);
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.error("getEntAccountByEntId", e.getMessage());
			return null;
		}
		return ea;
	}

	/**
	 * 根据计划付款id查询融资记录
	 * 
	 * @date 2017年12月20日 @user hsg
	 */
	@Override
	public CreditRecord findCreditRecordById(Long payId, Long tid) {
		logger.info("### 根据计划付款id查询融资记录(findCreditRecordByPayiId) start,参数payId={}", payId);
		CreditRecord findCreditRecordInfo = null;
		try {
			findCreditRecordInfo = creditUserServiceUtil.findCreditRecordInfo(payId, tid);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("### 根据计划付款id查询融资记录(findCreditRecordByPayiId) 发生异常 errMsg={},参数payId={}", e, payId);
		}
		return findCreditRecordInfo;

	}

	/**
	 * 根据id查询贷款资质申请记录
	 */
	@Override
	public CreditApplication findCreditApplicationById(Long tid) {
		logger.info("### 根据id查询贷款资质申请记录 start tid={}",tid);
		CreditApplication ca = new CreditApplication();
		CreditApplicationEntity cae = creditApplicationRepository.findOne(tid);
		if (cae != null) {
			BeanUtils.copyProperties(cae, ca);
		}
		return ca;
	}

	/**
	 * 查询企业是否开通筑保通
	 * 
	 * @date 2018年1月9日 @user hsg
	 */
	@Override
	public Boolean findEntCrProdByType(Long entId, String entType) {
		logger.info("### 查询企业是否开通筑保通 start 企业id entId={},entType={}",entId,entType);
		EntAccountEntity eae = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, entId, entType);
		if (eae == null) {
			return false;
		}
		List<EntCrProdEntity> ecpe = entCrProdEntityRepository.findByAccIdList(eae.getTid(), HelpConstant.Status.delete, ZhuCaiProdType.ZHU_CAI_B_TONG.toString(),
				EnCrStatus.PASS.toString());
		if (CollectionUtils.isNotEmpty(ecpe)) {
			return true;
		}
		return false;
	}

	/**
	 * 我的筑保通页面加载融资信息 TODO
	 */
	@Override
	public CreditRecordForm findRecordInfo(CreditRecord cr, Pageable pa) {
		logger.info("### 查询筑保通页面信息start--，parm={}", cr.toString());
		CreditRecordForm crf = new CreditRecordForm();
		if (cr.getCreditStatus().equals("WAIT_CONFIRM_PUR") || cr.getCreditStatus().equals("WAIT_CONFIRM_SUP")) {
			crf.setCreditStatus(CreditStatus.WAIT_CONFIRM.toString());
		} else {
			crf.setCreditStatus(cr.getCreditStatus());
		}
		logger.info("### 筑保通页面统计类的信息--，data={}", crf);

		// 查询筑保通列表数据 ---当融资状态是待发起不执行
		if (cr.getCreditStatus() != null && !"WAIT_SUBMIT".equals(cr.getCreditStatus())) {
			CreditRecordForm creditRecordForm = findCreditRecordList(cr, pa);
			crf.setCreditRecordPage(creditRecordForm.getCreditRecordPage());
			crf.setWaitPayAllAmt(creditRecordForm.getWaitPayAllAmt());
		}
		// 查询筑保通页面红签统计数字
		CreditRecordForm crAmount = findCountByAmount(cr);
		logger.info("### 查询筑保通页面红签统计数字--，data={}", crAmount);
		crf.setWithdrawalCount(crAmount.getWithdrawalCount());
		crf.setRepaymentCount(crAmount.getRepaymentCount());
		crf.setSigningContractCount(crAmount.getSigningContractCount());
		crf.setRepaymentedCount(crAmount.getRepaymentedCount());
		crf.setBreakContractCount(crAmount.getBreakContractCount());
		crf.setFailedFinanceCount(crAmount.getFailedFinanceCount());
		crf.setWaitConfirmCount(crAmount.getWaitConfirmCount());
		crf.setWaitConfirmPurCount(crAmount.getWaitConfirmPurCount());
		crf.setWaitPayCount(crAmount.getWaitPayCount());
		return crf;
	}

	/**
	 * 根据融资单号查询此融资单是否有成功支付的记录
	 */
	@Override
	public String getPayedCount(String[] recordNoArr) {
		List<String> payStatusList = new ArrayList<>();
		for (String recordNo : recordNoArr) {
			PaymentOrderEntity poe = paymentOrderRepository.findByStatusNotAndOrderNo(HelpConstant.Status.delete, recordNo);
			payStatusList.add(poe.getPayStatus());
			if(poe.getOrderAmt().compareTo(BigDecimal.ZERO) == 0) {
				paymentOrderRepository.updatePayStatusById(poe.getTid());
				PaymentOrderEntity entity = paymentOrderRepository.findOne(poe.getTid());
				payStatusList.add(entity.getPayStatus());
				orderLoopService.changeOrderByRcordNo(entity.getOrderNo());
			}
		}
		if (payStatusList.contains("02") || payStatusList.contains("05")) {
			return "true";
		} else {
			// long timeMillis = System.currentTimeMillis();
			Arrays.sort(recordNoArr);
			StringBuilder sb = new StringBuilder();
			for (String string : recordNoArr) {
				sb.append(string);
			}
			int hashCode = sb.toString().hashCode();
			int abs = Math.abs(hashCode);

			StringBuilder sbu = new StringBuilder();
			PaymentRelationEntity pr = new PaymentRelationEntity();
			for (String string : recordNoArr) {
				sbu.append(string + ",");
			}
			pr.setPaySingleNo(abs + "");
			pr.setRecordNo(sbu.toString());
			PaymentRelationEntity findByPaySingleNo = paymentRelationRepository.findByPaySingleNo(abs + "");
			PaymentRelationEntity entity = new PaymentRelationEntity();
			// 关系表中不存在，保存
			if (findByPaySingleNo == null) {
				entity = paymentRelationRepository.save(pr);
				// 存在，更新
			} else {
				int i = paymentRelationRepository.updateByPaySingleNo(abs + "", sbu.toString());
				entity = paymentRelationRepository.findByPaySingleNo(abs + "");
			}
			return "false," + entity.getPaySingleNo();
		}
	}

	/**
	 * 新增发票
	 */
	@Override
	public Long createInvoice(CreditInvoice creditInvoice) {
		// TODO Auto-generated method stub
		CreditInvoiceEntity creditInvoiceEntity = new CreditInvoiceEntity();
		creditInvoiceEntity.setCreateUser(creditInvoice.getUserId());
		creditInvoiceEntity.setCreTime(new Date());
		creditInvoiceEntity.setInvoiceCode(creditInvoice.getInvoiceCode());
		creditInvoiceEntity.setInvoiceDate(creditInvoice.getInvoiceDate());
		creditInvoiceEntity.setInvoiceAmount(creditInvoice.getInvoiceAmount());
		creditInvoiceEntity.setInvoiceFileId(creditInvoice.getInvoiceFileId());
		creditInvoiceEntity.setInvoiceNo(creditInvoice.getInvoiceNo());
		creditInvoiceEntity.setInvoiceFileName(creditInvoice.getInvoiceFileName());
		CreditInvoiceEntity save = creditInvoiceRepository.save(creditInvoiceEntity);
		PaymentPlanEntity ppe = paymentPlanRepository.findOne(creditInvoice.getPaymentPlanId());
		ppe.setInvoiceFileId(save.getTid());
		paymentPlanRepository.save(ppe);
		return save.getTid();
	}

	/**
	 * 修改发票
	 */
	@Override
	public Integer updateInvoice(CreditInvoice creditInvoice) {
		// TODO Auto-generated method stub
		BigDecimal invoiceAmount = creditInvoice.getInvoiceAmount();
		String invoiceCode = creditInvoice.getInvoiceCode();
		String invoiceNo = creditInvoice.getInvoiceNo();
		// String invoiceFileUrl = creditInvoice.getInvoiceFileUrl();
		Date invoiceDate = creditInvoice.getInvoiceDate();
		Long invoiceFileId = creditInvoice.getInvoiceFileId();
		String invoiceFileName = creditInvoice.getInvoiceFileName();
		Integer count = creditInvoiceRepository.updateInvoice(invoiceAmount, invoiceCode, invoiceDate, invoiceNo, invoiceFileId, creditInvoice.getTid(), creditInvoice.getUserId(),
				invoiceFileName);
		if (count == 1) {
			PaymentPlanEntity ppe = paymentPlanRepository.findOne(creditInvoice.getPaymentPlanId());
			ppe.setInvoiceFileId(creditInvoice.getTid());
			paymentPlanRepository.updateInvoiceFileId(creditInvoice.getTid(), ppe.getTid());
		}
		return count;
	}

	@Override
	public CreditInvoice findInvoice(CreditInvoice creditInvoice) {
		// TODO Auto-generated method stub
		CreditInvoiceEntity cie = creditInvoiceRepository.findByTidAndStatusNot(creditInvoice.getTid(), HelpConstant.Status.delete);
		if (cie != null) {
			BeanUtils.copyProperties(cie, creditInvoice);
		} else {
			return null;
		}
		return creditInvoice;
	}

	@Override
	public Integer valInvoiceInfo(String invoiceCode, String invoiceNo, Long tid) {
		Integer count = 0;
		try {
			count = creditInvoiceRepository.valInvoiceInfo(invoiceNo, invoiceCode, tid);
			// 如果返回1,判断此发票id是否被付款计划正常持有
			if (count >= 1) {
				CreditInvoiceEntity cie = creditInvoiceRepository.findByStatusNotAndInvoiceNoAndInvoiceCode(HelpConstant.Status.delete, invoiceNo, invoiceCode);
				PaymentPlanEntity ppe = paymentPlanRepository.findByStatusNotAndInvoiceFileId(HelpConstant.Status.delete, cie.getTid());
				// 如果ppe == null 表示此发票没有被正常持有
				if (ppe == null) {
					count = 0;
					// 物理删除此发票记录
					cie.setStatus(HelpConstant.Status.delete);
					creditInvoiceRepository.deleteById(cie.getTid());
				}
			}
		} catch (Exception e) {
			return 0;
		}
		return count;
	}

	@Override
	public CreditInvoice findInvoiceById(Long tid) {
		// TODO Auto-generated method stub
		CreditInvoice creditInvoice = new CreditInvoice();
		CreditInvoiceEntity cie = creditInvoiceRepository.findByTidAndStatusNot(tid, HelpConstant.Status.delete);
		BeanUtils.copyProperties(cie, creditInvoice);
		return creditInvoice;
	}


	@Override
	public CreditProduct findCreditProductByTid(Long tid) {
		if (tid == null) {
			return null;
		}
		CreditProductEntity cpe = creditProductRepository.findOne(tid);
		CreditProduct cp = new CreditProduct();
		if (cpe != null) {
			BeanUtils.copyProperties(cpe, cp);
			return cp;
		} else {
			return null;
		}

	}

	/**
	 * 查询融资历时记录
	 * 
	 * @author hsg
	 * @version 2018年7月26日
	 * @param recordId
	 * @param timeType
	 * @return
	 */
	@Override
	public CreditRecordTime findRecordTimeInfo(Long recordId, String timeType) {
		List<CreditRecordTimeEntrity> findByCrRecordIdAndType = creditRecordTimeRepository.findByCrRecordIdAndType(recordId, timeType);

		if (CollectionUtils.isNotEmpty(findByCrRecordIdAndType)) {
			if (findByCrRecordIdAndType.size() > 1) {
				logger.error("### 查询融资历时记录查来多条 recordId={}，timeType={} ", recordId, timeType);
			}
			CreditRecordTime creditRecordTime = new CreditRecordTime();
			BeanUtils.copyProperties(findByCrRecordIdAndType.get(0), creditRecordTime);
			return creditRecordTime;
		}
		return null;
	}

	@Override
	public CreditRecordTime addRecordTimeInfo(Long recordId, String recordNo, String timeType) {
		if (recordId == null && recordNo != null) {
			CreditRecordEntrity findByRecordNo = creditRecordRepository.findByRecordNo(recordNo);
			recordId = findByRecordNo.getTid();
		}
		CreditRecordTimeEntrity createRecordTime = creditUserServiceUtil.createRecordTime(recordId, timeType);
		if (createRecordTime != null) {
			CreditRecordTime creditRecordTime = new CreditRecordTime();
			BeanUtils.copyProperties(createRecordTime, creditRecordTime);
			return creditRecordTime;
		}
		return null;
	}

	@Override
	public CreditRecord addCrRecord(CreditRecord cr) {
		CreditRecordEntrity cre = creditRecordRepository.findByStatusNotAndPaymentId(HelpConstant.Status.delete, cr.getPaymentId());
		// 融资申请的金融id(采购商)
		EntAccountEntity purent = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getOriginatorEnterpriseId(),
				EntType.PURCHASER.toString());
		EntAccountEntity supent = entAccountRepository.findByStatusNotAndEnterpriseIdAndEntType(HelpConstant.Status.delete, cr.getParticipatorEnterpriseId(),
				EntType.SUPPLIER.toString());
		if (purent == null) {
			throw new RuntimeException("融资申请失败：查询采购商金融信息失败");
		}
		if (supent == null) {
			throw new RuntimeException("融资申请失败:查询供应商金融信息失败");
		}
		if(cr.getDaiBanBol() != null && cr.getDaiBanBol()){
			CreditProductEntity cpe = creditProductRepository.findByCrProdTypeAndStatusNot(CrProdType.E_POINT.toString(), HelpConstant.Status.delete);
			cr.setCrProdId(cpe.getTid());
		}
		if (cre != null) {
			cre.setCrProdId(cr.getCrProdId());
			//更新融资银行
			if(cr.getDaiBanBol() == null || !cr.getDaiBanBol()){
				creditRecordRepository.updateBankProd(null, cre.getTid(), cr.getCrProdId());
			}
			BeanUtils.copyProperties(cre, cr);
			return cr;
		}
		// 查询贷款资质申请记录
		CreditApplicationEntity cae = creditApplicationRepository.
				findCoopInfo(HelpConstant.Status.delete,supent.getTid(), purent.getTid(), CrAprovalStatus.BANK_SUCCESS.toString(),cr.getCrProdId());
		
		cre = new CreditRecordEntrity();
		// 贷款机构
		cre.setCrProdId(cr.getCrProdId());
		// 合同id
		cre.setContractId(cr.getContractId());
		// 合同编号
		cre.setContractNum(cr.getContractNum());
		// 账款金额
		cre.setCreditGetAmount(cr.getCreditAmount());
		// 融资金额
		cre.setCreditAmount(BigDecimal.ZERO);
		// 供应商组织机构
		cre.setParticipatorOrgnCode(supent.getOrgNum());
		// 供应商企业id
		cre.setParticipatorEnterpriseId(cr.getParticipatorEnterpriseId());
		// 账款到期日
		cre.setLoanDate(cr.getLoanDate());

		cre.setOriginator(purent.getTid());
		// 融资发起用户
		cre.setOriginatorUserId(cr.getOriginatorUserId());
		// 采购商组织机构
		cre.setOriginatorOrgnCode(purent.getOrgNum());
		// 采购商企业id
		cre.setOriginatorEnterpriseId(cr.getOriginatorEnterpriseId());
		// 融资参与者的金融id(供应商)
		cre.setParticipator(supent.getTid());

		cre.setAppNum(cae.getAppNum());
		// 付款单号
		cre.setPaymentNum(cr.getPaymentNum());
		// 付款计划id
		cre.setPaymentId(cr.getPaymentId());
		// 融资编号
		cre.setRecordNo(cr.getRecordNo());
		// 融资正常状态
		cre.setCreditUnusualStatus(CreditUnusualStatus.NORMAL.toString());
		cre.setCreditStatus(CreditStatus.WAIT_SUBMIT.toString());
		// 项目id
		cre.setProjectTid(cr.getProjectTid());
		creditRecordRepository.save(cre);
		return cr;
	}

	@Override
	public CreditApplication getCreditApplicationById(Long id) {
		CreditApplicationEntity findOne = creditApplicationRepository.findOne(id);
		if(findOne != null){
			CreditApplication ca = new CreditApplication();
			BeanUtils.copyProperties(findOne, ca);
			return ca;
		}
		return null;
	}

}